import random
import math
import KBEngine
import KBEDebug as log

# 每20分钟恢复一点体力
ENERGY_RECOVER_ONE_PER_SECONDS = 20 * 60


class AvatarOther(KBEngine.EntityComponent):

    def __init__(self):
        KBEngine.EntityComponent.__init__(self)

    # region kbengine method
    def onAttached(self, owner):
        log.DEBUG_MSG(f'AvatarOther onAttached: owner={owner.id}')

    def onDetached(self, owner):
        log.DEBUG_MSG(f'AvatarOther onDetached: owner={owner.id}')

    def onClientEnabled(self):
        log.DEBUG_MSG(f'AvatarOther onClientEnabled owner={self.owner.id}')

    def onClientDeath(self):
        log.DEBUG_MSG(f'AvatarOther onClientDeath owner={self.owner.id}')
        
    def onAvatarEnabled(self):
        self.pushInviteLists()

    def shareGetProp(self):
        if self.shareCnt > 0:
            self.shareCnt -= 1
            self.randomProp += 1
            self.client.onShareGetProp(0)
        else:
            self.client.onShareGetProp(1)

    def useProp(self, propId):
        if propId == 1:
            if self.matchProp > 0:
                self.matchProp -= 1
                self.client.onUseProp(0, propId)
            else:
                self.client.onUseProp(1, propId)
        elif propId == 2:
            if self.randomProp > 0:
                self.randomProp -= 1
                self.client.onUseProp(0, propId)
            else:
                self.client.onUseProp(1, propId)
        elif propId == 3:
            if self.moveProp > 0:
                self.moveProp -= 1
                self.client.onUseProp(0, propId)
            else:
                self.client.onUseProp(1, propId)

    def randomIsland(self):
        num = random.randint(0, 29)
        log.DEBUG_MSG(f'随机的岛屿编号为{num}')

    def purchaseProp(self, propId):
        if self.coin < 300:
            self.client.onPurchaseProp(1)
            return
        if propId == 7:
            self.moveProp += 1
        elif propId == 8:
            self.matchProp += 1
        elif propId == 9:
            self.randomProp += 1
        else:
            self.client.onPurchaseProp(2)
            return
        self.coin -= 300
        self.client.onPurchaseProp(0)
        log.INFO_MSG(f'user {self.owner.playerId} purchase prop {propId}')

    def purchasePropInGame(self, propId):
        if propId == 1 or propId == 2 or propId == 3:  # 购买道具
            if self.coin < 300:
                self.client.onPurchasePropInGame(1, propId)
                return
            if propId == 1:
                self.moveProp += 1
            elif propId == 2:
                self.matchProp += 1
            elif propId == 3:
                self.randomProp += 1
            self.coin -= 300
            self.client.onPurchasePropInGame(0, propId)
        elif propId == 4:  # 延时道具
            if self.coin < 50:
                self.client.onPurchasePropInGame(1, propId)
                return
            self.coin -= 50
            self.client.onPurchasePropInGame(0, propId)
        else:  # 复活(暂时不做)
            pass
        log.INFO_MSG(f'purchasePropInGame {self.owner.playerId} purchase prop {propId}')

    def adsPropInGame(self, propId):
        if propId == 1 or propId == 2 or propId == 3:  # 购买道具
            # if self.coin < 300:
            #     self.client.onAdsPropInGame(1, propId)
            #     return
            if propId == 1:
                self.moveProp += 1
            elif propId == 2:
                self.matchProp += 1
            elif propId == 3:
                self.randomProp += 1
            self.client.onAdsPropInGame(0, propId)
        elif propId == 4:  # 延时道具
            # if self.coin < 50:
            #     self.client.onAdsPropInGame(1, propId)
            #     return
            self.client.onAdsPropInGame(0, propId)
        else:  # 复活(暂时不做)
            pass
        #广告数增加1
        KBEngine.baseAppData['Lobby'].updateAds()
        log.INFO_MSG(f'onAdsPropInGame {self.owner.playerId} ads prop {propId}')

    def recharge(self, prop_id, boc):
        KBEngine.baseAppData['Lobby'].checkTransaction(self.owner, boc, prop_id)

    def repRecharge(self, state, prop_id):
        if state == 1:
            self.client.onRecharge(-1)
            return
        else:
            add_coin = 0
            if prop_id == 1:
                add_coin = 1200
            elif prop_id == 2:
                add_coin = 2500
            elif prop_id == 3:
                add_coin = 6500
            elif prop_id == 4:
                add_coin = 20000
            elif prop_id == 5:
                add_coin = 45000
            elif prop_id == 6:
                add_coin = 140000
            log.INFO_MSG(f'recharge {self.owner.playerId} pay {prop_id}')
            self.client.onRecharge(add_coin)
            self.coin += add_coin

    def inFirstGame(self):
        if self.firstGame == 0:
            self.owner.client.onLayEggs()
            self.client.onFirstGame()
            self.firstGame = 1

    def guideTest(self):
        self.owner.client.onLayEggs()
        self.client.onFirstGame()

    def recordInviteLst(self, invite_id, nickName):
        KBEngine.baseAppData['Lobby'].record_invite_player(invite_id, self.owner.playerId, nickName, len(self.owner.farm.chickens))

    def recordPlatform(self, platform_id):
        KBEngine.baseAppData['Lobby'].updateOrCreateRecord(platform_id)

    def updateState(self):
        self.firstGameInInvite = 1

    def addInviteInfo(self, info):
        if info not in self.invite_lst:
            self.invite_lst.append(info)
            self.invite_lst = self.invite_lst
            # 奖励
            #self.online_avatars[invite_id].avatarOther.coin += 100
            self.point += 100
            self.coin += 500

    def pushInviteLists(self):
        total_count = len(self.invite_lst)
        # 如果list太长，切片太多，服务端发送很多数据包，导致socket会断开
        # eg.list长度为39982，切片为10，需要发送接近4000个包，发完后，socket就断开了，导致玩家重复断线重连
        slice_num = 100
        slice_count = math.ceil(total_count / slice_num)
        if(slice_count > 10):
            slice_count = 10
        for i in range(slice_count):
            start = i * slice_num
            end = start + slice_num
            self.client.onPushInviteLists(self.invite_lst[start:end], i, total_count, slice_count)
    
    def reqPushInviteLists(self, slice_total_count):
        total_count = len(self.invite_lst)
        slice_num = 100
        slice_count = math.ceil(total_count / slice_num) - slice_total_count
        if(slice_count > 10):
            slice_count = 10
        for i in range(slice_count):
            start = (i + slice_total_count) * slice_num
            end = start + slice_num
            self.client.onPushInviteLists(self.invite_lst[start:end], i + slice_total_count, total_count, slice_total_count + slice_count)
        
    def dailyRefresh(self):
        self.seasonCount = 4
        self.freePlayCount = 3
        self.shareCount = 0
        self.seasonShareCount = 0
        self.todayPublicCnt = 0
        self.todaySeasonCnt = 0

    def startGame(self, gameType):
        log.DEBUG_MSG(f'startGame: {self.owner.playerId} {gameType}')
        usingType = 0
        if gameType == 1:
            difficulty = 1
            if self.freePlayCount > 0:
                self.freePlayCount -= 1
            elif self.shareCount > 0:
                self.shareCount -= 1
                usingType = 1
            else:
                if self.coin < 100:
                    self.client.onGameStart(1, gameType, difficulty, usingType)
                    return
                else:
                    self.coin -= 100
                    usingType = 2
            self.todayPublicCnt += 1
        else:
            difficulty = 2
            if self.seasonCount > 0:
                self.seasonCount -= 1
            else:
                if self.todaySeasonCnt < 6:
                    self.client.onGameAdsStart()
                    return
                if self.coin < 100:
                    self.client.onGameStart(1, gameType, difficulty, usingType)
                    return
                else:
                    usingType = 2
                    self.coin -= 100
            self.todaySeasonCnt += 1

        KBEngine.baseAppData['Lobby'].addChallengeCount(self.owner.playerId)
        self.client.onGameStart(0, gameType, difficulty, usingType)

    def adsStartGame(self):
        self.todaySeasonCnt += 1
        KBEngine.baseAppData['Lobby'].addChallengeCount(self.owner.playerId)
        self.client.onGameStart(0, 2, 2, 0)
        KBEngine.baseAppData['Lobby'].updateAds()
        log.INFO_MSG(f'adsStartGame {self.owner.playerId}')
        
    def gameFinish(self, is_win, gameMode):
        log.INFO_MSG(f'gameFinish[{self.owner.databaseID}] [{self.owner.playerId}] is_win: {is_win}')
        if is_win == 0:
            self.catchCount += 1
            self.point += 100
            self.owner.rank.updateCatchCount()
            KBEngine.baseAppData['Lobby'].addCompleteCount(self.owner.playerId)
            if gameMode == 1:  # normal难度
                self.owner.task.completeTask(3, 0)
            else:  # hard难度
                self.owner.task.completeTask(4, 0)
            # 赛季通关给鸡
            self.owner.farm.rewardChicken(gameMode)
        self.client.onGameEnd(0)
